package com.chen.bpsptsystem.qiniu;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @CLASSNAME QiniuUtils
 * @DESCRIPTION 描述
 * @AUTHOR chen
 * @DATE 2018-11-22 9:28
 **/
@Slf4j
public class QiniuUtils {
    // 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "S7o8oK00esVkwtSx0JJj8OyfkyMkJod2PlLskiS2";
    private static final String SECRET_KEY = "frox6C3prGCCS6s0ylriokMx7wYST3BfeoK3ZSiM";
    // 要上传的空间
    private static final String bucketname = "newimg";
    //水印接口
    private static final String WATERMAKER = "imageView2/0/q/75|watermark/1/image/aHR0cHM6Ly9vanBibHkxdW4ucW5zc2wuY29tL2xvZ28ucG5n/dissolve/100/gravity/SouthEast/dx/10/dy/10|imageslim";

//    String url = "http://pijdovo2n.bkt.clouddn.com/"; //已过期
    String url = "http://pp0i45ol9.bkt.clouddn.com/";

    //构造一个带指定Zone对象的配置类 Zone.zone2() 华南,one.zone0()华东
    Configuration cfg = new Configuration( Zone.zone2() );
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager( cfg );

    public String upload(MultipartFile file) throws Exception {
        String path = "d:\\profile\\";
//        String path = "/root/pic";
        File f = new File( path );
        if (!f.exists()){
            f.mkdirs();
        }
        String originName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + originName.substring( originName.lastIndexOf( "." ) );
        File newFile = new File( path + newName );

        file.transferTo( newFile );
        String localPath = path + newName;
        String key = null;
        Auth auth = Auth.create( ACCESS_KEY, SECRET_KEY );
        String upToken = auth.uploadToken( bucketname );
        try {
            Response response = uploadManager.put( localPath, key, upToken );
            DefaultPutRet putRet = new Gson().fromJson( response.bodyString(), DefaultPutRet.class );
            String imgUrl = url + putRet.hash;
            return imgUrl;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.info( r.toString() );
//            System.err.println( r.toString() );
            try {
                log.info( r.bodyString()  );
//                System.err.println( r.bodyString() );
            } catch (QiniuException ex2) {
                //ignore
                log.info( ex2.getMessage() );
            }
        }
        return null;
    }


}